package com.pucheng.bracelet.viewmodel

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.clj.fastble.exception.BleException
import com.pucheng.bracelet.app.ble.BleCmd
import com.pucheng.bracelet.app.ble.BleWriteAndNotifyCallback
import com.pucheng.bracelet.app.ble.ClientManager
import com.pucheng.bracelet.app.ext.KEY_IS_12_UNIT
import com.pucheng.bracelet.app.ext.KEY_OPEN_ALL_DAY_HR_MEASURE
import com.pucheng.bracelet.app.ext.KEY_QUICK_VIEW
import com.pucheng.bracelet.app.ext.KEY_SIT_FOR_A_LONG
import com.pucheng.bracelet.app.network.apiService
import com.pucheng.bracelet.app.network.stateCallback.ListDataUiState
import com.pucheng.bracelet.app.util.ByteUtils
import com.pucheng.bracelet.app.util.CacheUtil
import com.pucheng.bracelet.data.bean.FeedbackBean
import com.zaaach.citypicker.model.City
import com.zaaach.citypicker.util.CityComparator
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request
import java.util.*

class SettingViewModel : BaseViewModel() {

    val bind = MutableLiveData<Boolean>().apply {
        value = if (CacheUtil.getWatchInfo() != null) {
            !TextUtils.isEmpty(CacheUtil.getWatchInfo()!!.mac)
        } else {
            false
        }
    }
    val is12Unit = MutableLiveData<Boolean>().apply {
        value = CacheUtil.getTimeSystem()
    }

    val isSitRemind = MutableLiveData<Boolean>().apply {
        value = CacheUtil.isSitRemind()
    }

    val isOpenHRMeasure = MutableLiveData<Boolean>().apply {
        value = CacheUtil.isOpenHRMeasure()
    }

    val isQuickView = MutableLiveData<Boolean>().apply {
        value = CacheUtil.getQuickView()
    }

    val effectivePeriodTime = MutableLiveData<String>().apply {
        value = CacheUtil.getQuickViewPeriod()
    }
    val doNotDisturb = MutableLiveData<String>().apply {
        value = CacheUtil.getDoNotDisturb()
    }

    //城市数据
    var cityDatas: MutableLiveData<List<City>> = MutableLiveData()

    /**
     * 查找手表
     */
    fun findWatch() {
        ClientManager.getInstance()
            .sendControlCmd(BleCmd.FIND_WATCH, object : BleWriteAndNotifyCallback() {
                override fun onCharacteristicChanged(data: ByteArray?) {
//                if (data!![1] == 0x07 as Byte && data!![2] == 0x01 as Byte ){
//                    showMsg("查找手环成功")
//                }
                }

                override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
                }

                override fun onWriteFailure(exception: BleException?) {
                    showMsg("查找手环失败")
                }
            })
    }

    /**
     * 恢复出厂设置
     */
    fun reStoreSysSetting() {
        ClientManager.getInstance()
            .sendControlCmd(BleCmd.RESTORE_SYS_SETTING, object : BleWriteAndNotifyCallback() {
                override fun onCharacteristicChanged(data: ByteArray?) {
                    if (data!![1] == 0x0C.toByte() && data!![2] == 0x01.toByte()) {
                        showMsg("恢复出厂设置成功")
                        bind.value = false
                    }
                }

                override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
                }

                override fun onWriteFailure(exception: BleException?) {
                    showMsg("恢复出厂设置失败")
                }
            })
    }

    fun chageTimeUnit(is12Unit: Boolean) {
        ClientManager.getInstance().sendControlCmd(
            String.format(
                BleCmd.SET_TIME_UNIT, if (is12Unit) {
                    "01"
                } else {
                    "00"
                }
            ), object : BleWriteAndNotifyCallback() {
                override fun onCharacteristicChanged(data: ByteArray?) {
                    if (data!![1] == ByteUtils.intToByte(7) && data!![2] == ByteUtils.intToByte(1)) {
                        CacheUtil.setTimeSystem(is12Unit)
                        this@SettingViewModel.is12Unit.value = is12Unit
                    }
                }

                override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
                }

                override fun onWriteFailure(exception: BleException?) {
                }
            })
    }

    /**
     * 久坐提醒开关
     */
    fun sitForALongHintRemind(isOpen: Boolean) {
        ClientManager.getInstance().sendControlCmd(
            String.format(
                BleCmd.SIT_FOR_A_LONG, if (isOpen) {
                    "01"
                } else {
                    "00"
                }
            ), object : BleWriteAndNotifyCallback() {
                override fun onCharacteristicChanged(data: ByteArray?) {
                    if (data!![1] == ByteUtils.intToByte(9) && data!![2] == ByteUtils.intToByte(1)) {
                        CacheUtil.setOpenSitRemind(isOpen)
                        this@SettingViewModel.isSitRemind.value = isOpen
                    }
                }

                override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
                }

                override fun onWriteFailure(exception: BleException?) {
                }
            })
    }

    /**
     * 全天心率测量开关
     */
    fun openHRMeasure(isOpen: Boolean) {
        ClientManager.getInstance().sendControlCmd(
            String.format(
                BleCmd.OPEN_ALL_DAY_HR_MEASURE, if (isOpen) {
                    "0101"
                } else {
                    "0000"
                }
            ), object : BleWriteAndNotifyCallback() {
                override fun onCharacteristicChanged(data: ByteArray?) {
                    if (data!![1] == ByteUtils.intToByte(0x0A) && data!![2] == ByteUtils.intToByte(
                            0x01
                        )
                    ) {
                        CacheUtil.setOpenHRMeasure(isOpen)
                        this@SettingViewModel.isOpenHRMeasure.value = isOpen
                    }
                }

                override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
                }

                override fun onWriteFailure(exception: BleException?) {
                }
            })
    }

    /**
     * 翻腕亮屏设置
     */
    fun openQuickView(isOpen: Boolean) {
        ClientManager.getInstance().sendControlCmd(
            BleCmd.getQuickViewCmd(isOpen), object : BleWriteAndNotifyCallback() {
                override fun onCharacteristicChanged(data: ByteArray?) {
                    if (data!![1] == ByteUtils.intToByte(0x0B) && data!![2] == ByteUtils.intToByte(
                            0x01
                        )
                    ) {
                        CacheUtil.setOpenQuickView(isOpen)
                        this@SettingViewModel.isQuickView.value = isOpen
                    }
                }

                override fun onWriteSuccess(current: Int, total: Int, justWrite: ByteArray?) {
                }

                override fun onWriteFailure(exception: BleException?) {
                }
            })
    }


    private fun showMsg(msg: String) {
        ToastUtils.showLong(msg)
    }


    /**
     * 获取faq
     */
    fun getCitys() {
        request({ apiService.getArea("中国", "深圳", "113°46", "22°24") }, {
            //请求成功
            val comparator = CityComparator()
            Collections.sort(it, comparator)
            cityDatas.value = it
        }, {
            //请求失败
            val dataUiState =
                ListDataUiState(
                    isSuccess = false,
                    errMessage = it.errorMsg,
                    listData = arrayListOf<FeedbackBean>()
                )
            cityDatas.value = arrayListOf()
        })
    }
}
